/*   Copyright 2010 Jonathan Wagner
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 */
package com.alienos.collide.bounds;

import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

import com.alienos.collide.event.CollisionEvent;
import com.alienos.collide.event.CollisionListener;

public class UnitTestCollisionClient<I> implements CollisionListener<I> {

    private final ConcurrentMap<I, Set<I>> collisions = new ConcurrentHashMap<I, Set<I>>();

    @Override
    public void collide(CollisionEvent<I> e) {

        if (e.CollisionType() == CollisionEvent.Type.Enter) {
            doCollide(e);
        } else {
            doUnCollide(e);
        }
    }

    private void doCollide(CollisionEvent<I> e) {
        addCollision(e.getTargetId(), e.getRecipientId());
        addCollision(e.getRecipientId(), e.getTargetId());
    }

    private void doUnCollide(CollisionEvent<I> e) {
        removeCollision(e.getTargetId(), e.getRecipientId());
        removeCollision(e.getRecipientId(), e.getTargetId());
    }

    private void addCollision(I key, I collider) {
        Set<I> cols = collisions.get(key);

        if (null == cols) {
            cols = new HashSet<I>();
            collisions.put(key, cols);
        }

        cols.add(collider);
    }

    private void removeCollision(I key, I collider) {
        collisions.get(key).remove(collider);
    }

    public Set<I> collisionsFor(I id) {
        Set<I> col = collisions.get(id);

        if (null == col) {
            return Collections.emptySet();
        } else {
            return col;
        }
    }
}
